<?php

declare(strict_types=1);

namespace App\Controller;

use App\HscoinConf;
use App\Service\FundConfService;
use App\Service\HscoinConfService;
use App\Service\HscoinStatsService;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use function Hyperf\Config\config;
use function Hyperf\Support\env;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;

#[Controller]
class ConfController extends AbstractController
{
    #[Inject]
    private HscoinConfService $service;
    #[Inject]
    private HscoinStatsService $statsService;
    #[Inject]
    protected ValidatorFactoryInterface $validationFactory;

    /**
     * @todo valid
     */


    function getConf()
    {
        $data = $this->service->getAll();
        return $this->jsonSuccess($data);
    }

    function setAppEnabled(RequestInterface $request)
    {

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'app_enabled' => ['required', "in:-1,1"],
            ],
            [
                'app_enabled.required' => '状态必填',
                'app_enabled.in' => '启用值1或-1',
            ]
        );
        if ($validator->fails()) {
            return $this->jsonError($validator->errors()->first());
        }
        $data = $validator->validated();
        $rs = $this->service->save($data);
        return $this->jsonSuccess(['success' => $rs]);
    }

    function getAppEnabled()
    {
        $rs = $this->service->get(HscoinConf::FIELD_APP_ENABLED, 1);
        return $this->jsonSuccess($rs);
    }

    public function store(RequestInterface $request)
    {
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'app_name' => ['required', 'string', 'min:2', 'max:20'],
                'app_base_amount' => ['required', 'numeric', 'gt:0'],

            ],
            [
                'app_name.required' => '财富池名称2-20字符',
                'app_name.string' => '财富池名称字符串',
                'app_base_amount.numeric' => '基础奖金数字',
                'app_base_amount.gt' => '基础奖金大于0',

            ]
        );
        if ($validator->fails()) {
            return $this->jsonError($validator->errors()->first());
        }

        $data = $this->request->post();
        $rs = $this->service->save($data);
        if (isset($data['app_base_amount'])) {
            $this->statsService->updateBaseAmount($data['app_base_amount']);
        }
        return $this->jsonSuccess($rs);
    }

}
